<template>
  <div>
    <!-- 页面头部 -->
    <header>
      <div class="logo">
        <h1>Raccoon Guide</h1>
      </div>
      <div class="header-links">
        <button v-if="!userName" @click="goToLogin" class="login-btn">Login</button>
        <div v-if="userName">Hello, {{ userName }}</div>
        <button v-if="userName" @click="handleLogout" class="layout-btn">Layout</button>
        <button @click="goToStar" class="star-btn">Star</button>
        <button v-if="userName" @click="showLinkPopup = true" class="new-link-btn">New Link</button>
      </div>
    </header>

    <!-- 内容区域 -->
    <main>
      <h2>Link List</h2>
      <table id="link-list-container">
        <thead>
          <tr>
            <th>Name</th>
            <th>Description</th>
            <th>URL</th>
            <th>Ratings</th>
            <th v-if="userName">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="link in links" :key="link.id">
            <td>{{ link.name }}</td>
            <td>{{ link.info }}</td>
            <td>{{ link.url }}</td>
            <td>{{ link.bayesian_ratings.toFixed(1) }}</td>
            <td v-if="userName">
              <div class="actions">
                <button @click="handleLike(link.id)" :disabled="link.liked">Like</button>
                <button @click="handleDislike(link.id)" :disabled="link.disliked">dislike(Hide) </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </main>

    <!-- Toast Message -->
    <div v-if="showToast" class="toast">Action successful!</div>

    <!-- New Link Popup -->
    <div v-if="showLinkPopup" class="popup">
      <div class="popup-content">
        <h3>Submit New Link</h3>
        <input v-model="newLinkName" type="text" placeholder="Link Name" required />
        <textarea v-model="newLinkDescription" placeholder="Link Description" required></textarea>
        <textarea v-model="newLinkUrl" placeholder="Link Url" required></textarea>
        <button @click="submitNewLink" :disabled="!newLinkName || !newLinkDescription || !newLinkUrl">Submit</button>
        <button @click="showLinkPopup = false">Cancel</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'HomePage',
  setup() {
    const router = useRouter();
    const userName = ref(localStorage.getItem('userName') || '');
    const userId = ref(localStorage.getItem('userId') || '');
    const links = ref<any[]>([]);
    const showToast = ref(false);
    const showLinkPopup = ref(false);  // 控制气泡显示
    const newLinkName = ref('');
    const newLinkDescription = ref('');
    const newLinkUrl = ref('');

    // 获取所有链接数据
    const fetchLinks = async () => {
      try {
        let req_url = 'http://localhost:7777/getRaccoonLink'
        if(localStorage.getItem('userId')){
          req_url='http://localhost:7777/getRaccoonLink?userId='+localStorage.getItem('userId')
        }
        const response = await fetch(req_url);
        const data = await response.json();
        links.value = data.data || [];
      } catch (error) {
        console.error('Error fetching links:', error);
        alert('Failed to load links. Please try again later.');
      }
    };

    const goToLogin = () => {
      router.push('/login');
    };

    const handleLogout = () => {
      localStorage.removeItem('userName');
      localStorage.removeItem('userId');
      localStorage.removeItem('token');
      userName.value = '';
      userId.value = '';
      alert('Logged out successfully!');
      fetchLinks(); 
    };

    const goToStar = () => {
      router.push('/star');
    };

    // 处理喜欢点击
    const handleLike = async (linkId: string) => {
      if (!userId.value) {
        alert('Please log in to like the link.');
        return;
      }

      try {
        const response = await fetch('http://localhost:7777/addPositivePoint', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ link_id: linkId, userId: userId.value }),
        });

        const data = await response.json();
        if (data.message === 'Positive point added successfully') {
          await fetchLinks();  
          const link = links.value.find((link: any) => link.id === linkId);
          if (link) {
            link.liked = true;
          }
          showToast.value = true;
          setTimeout(() => showToast.value = false, 2000);  // 自动隐藏 Toast
        } else {
          alert(data.message);
        }
      } catch (error) {
        console.error('Error liking the link:', error);
        alert('An error occurred. Please try again.');
      }
    };

    // 处理不喜欢点击
    const handleDislike = async (linkId: string) => {
      if (!userId.value) {
        alert('Please log in to dislike the link.');
        return;
      }

      try {
        const response = await fetch('http://localhost:7777/addNegativePoint', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ link_id: linkId, userId: userId.value }),
        });

        const data = await response.json();
        if (data.message === 'Negative point added successfully') {
          await fetchLinks();  
          const link = links.value.find((link: any) => link.id === linkId);
          if (link) {
            link.disliked = true;
          }
          showToast.value = true;
          setTimeout(() => showToast.value = false, 2000);  // 自动隐藏 Toast
        } else {
          alert(data.message);
        }
      } catch (error) {
        console.error('Error disliking the link:', error);
        alert('An error occurred. Please try again.');
      }
    };

    const submitNewLink = async () => {
      if (!newLinkName.value || !newLinkDescription.value || !newLinkUrl.value) {
        alert('Please provide all necessary details.');
        return;
      }

      try {
        const response = await fetch('http://localhost:7777/submitNewLink', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: userId.value,
            name: newLinkName.value,
            info: newLinkDescription.value,
            url: newLinkUrl.value,
          }),
        });

        const data = await response.json();
        if (data.message === 'Link add successfully') {
          // 更新本地链接列表
          await fetchLinks();  // 重新获取链接列表

          showToast.value = true;
          setTimeout(() => {
            showToast.value = false;
          }, 2000);  // 自动隐藏 Toast

          // 清空输入框和关闭弹出框
          newLinkName.value = '';
          newLinkDescription.value = '';
          newLinkUrl.value = '';
          showLinkPopup.value = false;
        } else {
          alert(data.message);
        }
      } catch (error) {
        console.error('Error submitting new link:', error);
        alert('An error occurred. Please try again.');
      }
    };

    onMounted(() => {
      fetchLinks();
    });

    return {
      userName,
      links,
      showToast,
      showLinkPopup,
      newLinkName,
      newLinkDescription,
      newLinkUrl,
      goToLogin,
      handleLogout,
      goToStar,
      handleLike,
      handleDislike,
      submitNewLink,
    };
  },
};
</script>

<style scoped>

.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; 
}

.popup-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.popup-content input,
.popup-content textarea {
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.popup-content button {
  padding: 10px 15px;
  font-size: 16px;
  margin-top: 10px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
}

.popup-content button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}


.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #4caf50;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  display: inline-block;
  z-index: 9999;
}


header {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #f8f8f8;
  border-bottom: 2px solid #ccc;
  position: relative; 
}

header .logo h1 {
  margin: 0;
}


header .header-links {
  position: absolute;
  top: 10px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 15px; 
}

header .header-links button {
  margin-left: 15px;
}

main {
  padding: 20px;
  margin-top: 60px; 
}


table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed; 
}

th, td {
  padding: 10px;
  border: 1px solid #ddd;
  text-align: left;
  word-wrap: break-word; 
}

th {
  background-color: #f4f4f4;
}

.actions {
  display: flex;
  gap: 10px;
}

.link-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #fafafa;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.link-item .actions {
  display: flex;
  gap: 10px;
}
</style>


